<template>
  <div>
    <div ref="commentsTop"></div>
    <div
      v-show="comments.length || commentReplyDisplay || loading"
      v-loading="loading"
      class="sub-comments-list m-t-10"
      :style="loading ? 'min-height: 4rem;' : ''"
    >
      <reply-container
        ref="commentReply"
        v-show="commentReplyDisplay"
        :cur-comment-id="curComment.id"
        :receive-comment-id="curComment.id"
        :receive-user-id="curComment.author.id"
        :receive-user-nickname="curComment.author.nickname"
        @replied="repliedComment"
      />
      <comment-list-item
        v-for="item in comments"
        :key="item.id"
        :comment="item"
        :cur-comment-id="curComment.id"
        @repliedComment="repliedSubComment"
        @deletedComment="deletedSubComment"
      />
      <span v-if="curComment.subs > 3 && !pagination.current" class="info-deep f-mini">
        共有 {{ curComment.subs }} 条评论，
        <span class="link el-link--primary" @click="seeComments">点击查看</span>
      </span>
      <pagination
        :current-page="pagination.current"
        :page-count="pagination.count"
        :fixed-query="{ comment_id: curComment.id }"
        is-mini
        class="m-t-0"
      />
    </div>
  </div>
</template>

<script>
import { formatComments } from '../format';
import CommentListItem from './comment-list-item';
import ReplyContainer from './reply-container';

export default {
  name: 'comments-list',
  components: {
    CommentListItem,
    ReplyContainer,
  },
  props: {
    curComment: Object,
  },
  data() {
    return {
      loading: false,
      comments: [],
      pagination: {
        current: null,
        count: null,
      },
      receiver: {
        commentId: undefined,
        id: undefined,
        nickname: undefined,
      },
      commentReplyDisplay: false, // 用于回复回答的输入框
    };
  },
  computed: {
    isCurFloor() { return Number(this.$route.query.comment_id) === this.curComment.id; },
    // 加载楼中楼所需参数
    loadCommentsParams() {
      return {
        commentId: this.curComment.id,
        page: this.$route.query.sub_page,
      };
    },
  },
  mounted() {
    if (this.isCurFloor) {
      this.loadComments({ scroll: true });
    } else if (this.curComment.subs) { // 如果有回复，默认加载三条
      this.loadComments({ number: 3, page: 1 });
    }
  },
  methods: {
    // 加载楼中楼
    loadComments(obj = {}) {
      this.loading = true;
      const params = Object.assign({}, this.loadCommentsParams, obj);
      this.$api.comments.subIndex(params)
        .then((res) => {
          this.comments = formatComments(res.data);
          if (!params.number) { // 当限定了加载条数（默认加载）时，不整翻页
            this.pagination.current = res.kaminari.current_page;
            this.pagination.count = res.kaminari.total_pages;
          }
          if (params.scroll) { // 加载完成后再滚动到位置，不然会被之前的评论默认加载三条的高度影响
            this.scrollIntoCommentsTop();
          }
        })
        .catch(() => {})
        .then(() => { this.loading = false; });
    },
    // 要对跟帖写评论（父组件调用）
    handleReplyComment() {
      this.commentReplyDisplay = !this.commentReplyDisplay;
    },
    // 评论了跟帖
    repliedComment(comment) {
      this.$message.success('评论成功');
      this.commentReplyDisplay = false;
      this.comments.unshift(comment);
    },
    // 回复了评论
    repliedSubComment(comment) {
      this.comments.push(comment); // 插到最后
    },
    // 删除了评论
    deletedSubComment(comment) {
      this.comments.splice(this.comments.indexOf(comment), 1);
    },
    // 点击查看
    seeComments() {
      this.reloadQuery({
        comment_id: this.curComment.id,
        page: this.$route.query.page,
        self_comment_page: this.$route.query.self_comment_page, // 保留评论页码
        // 清空了子楼页码
      });
    },
    // 定位到当前评论列表开始位置
    scrollIntoCommentsTop() {
      this.$refs.commentsTop.scrollIntoView({ block: 'center' });
    },
  },
  watch: {
    loadCommentsParams(newVal, oldVal) {
      const changedComment = newVal.commentId !== oldVal.commentId; // 更换了正在查看的回答
      const changedSubPage = newVal.page !== oldVal.page; // 切换了子楼页码
      const scroll = !changedComment && changedSubPage;
      if (this.isCurFloor) this.loadComments({ scroll });
    },
  },
};
</script>

<style lang="scss">
.sub-comments-list {
  padding: .5rem 1rem;
  border: 1px solid #e5e5e5;
  border-radius: 4px;
}
</style>
